package nc.bs.arap.op;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import nc.bs.arap.util.PostUtil;
import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.impl.pubapp.pattern.database.TempTable;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.vo.pub.BusinessException;
import nc.vo.pub.JavaType;

public abstract class AbstractMdmOp {
	
	private BaseDAO dao = null;
	
	protected String temptable = "temp_pkid";

	public void exec(boolean isqc) {
		try {
			String sql = getSql(isqc);
			List<Map<String, Object>> list = query(sql);
			if(list != null && list.size() > 0) {
				int len = list.size();
				int starindex = 0;
				int page = 50;
				while(len >= starindex) {	
					String content = list2JSON(list, starindex, page);
					String result = send(content);
					sendAfter(result);
					
					starindex = starindex+page;
				}
				
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public BaseDAO getDao() {
		
		if(dao == null) {
			dao = new BaseDAO();
		}
		
		return dao;
	}
	
	protected abstract void sendAfter(String result) throws Exception ;

	public String send(String content) throws BusinessException {
		String urlKey = getUrlKey();
		
		return PostUtil.send(urlKey, content);
	}

	protected abstract String getUrlKey();

	protected abstract String getSql(boolean isqc);

	private String list2JSON(List<Map<String, Object>> list, int starindex, int page) {
		
		if(list != null && list.size() > 0) {
			JSONArray root = new JSONArray();
			JSONObject json = null;
			String key = null;
			Object value = null;
			int len = list.size();
			
			int temp = len < (starindex+page) ? len : (starindex+page);
			for(int i = starindex; i < temp; i ++) {
				json = new JSONObject();
				for(Iterator<String> iter = list.get(i).keySet().iterator(); iter.hasNext();) {
					key = iter.next();
					if(key.equals("tpk")) continue;
					value = list.get(i).get(key);
					if(value == null) value = "";
					json.put(key, value.toString());
				}
				
				root.add(json);
			}
			
			return root.toJSONString();
		}
		
		return null;
	}

	private List<Map<String, Object>> query(String sql) throws DAOException{
		
		List<Map<String, Object>> list = (List<Map<String, Object>>) getDao().executeQuery(sql, new MapListProcessor());
		
		
		TempTable bo = new TempTable();
		String[] columns = new String[] {"tpk"};
		String[] columnTypes = new String[] {"char(20)"};
		JavaType[] types = new JavaType[] {JavaType.String};
		List<List<Object>> listdata = new ArrayList<List<Object>>();
		for(Map<String, Object> map : list) {
			List<Object> inlist = new ArrayList<Object>();
			inlist.add(map.get("tpk"));
			listdata.add(inlist);
		}
		bo.getTempTable(temptable, columns, columnTypes, types, listdata);
		
		return list;
	}

	
	
}
